import { createWebHistory, createRouter } from 'vue-router'
import { useUserOut } from '@/store/user';
import {accountApi} from '@/api/user'

import Home from '../components/HomeView.vue'
import Book from '../components/BookView.vue'

const routes = [
  { path: '/', component: Home },
  { path: '/book', component: Book },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

const store = useUserOut()
router.beforeResolve(async (to, from, next) => {
  if (!store.authenticated) {
    try {
      const account = await accountApi()
      await store.setAuthentication(account.data); 
    } catch(e) {
      console.error(e)
    }
  }
  next();
})

export const setupRouter = (app) => {
  app.use(router)
}

export default router